import { Ollama } from 'ollama/browser'
import axios from 'axios'
import { fetchEventSource } from '@microsoft/fetch-event-source'

// const ollama = new Ollama({ host: 'http://127.0.0.1:8090' })
const ollama = new Ollama({ host: location.origin })

let sseCtrl = null

// reference:
// https://github.com/ollama/ollama-js
// https://github.com/ollama/ollama/blob/main/docs/api.md

export async function sseChat(
  model,
  userMsg,
  history,
  systemMsg,
  options = {},
  onMessageCallback,
  onCloseCallback,
  onErrorCallback
) {
  let token = localStorage.getItem('token')
  sseCtrl = new AbortController()

  fetchEventSource(`/sseChat/flux/ai/ollamaStreamV1`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
      // "X-Token": getCookie("Authorization") || "",
    },
    body: JSON.stringify({
      model,
      messages: [
        // { role: 'system', content: systemMsg },
        // ...history,
        { role: 'user', content: userMsg }
      ],
      stream: true,
      token: token
    }),
    signal: sseCtrl.signal,
    openWhenHidden: true,
    async onopen(response) {
      console.log('onopen', response)
    },
    onmessage(msg) {
      onMessageCallback(msg)
    },
    onclose() {
      pauseChat()
      onCloseCallback()
    },
    onerror(err) {
      pauseChat()
      onErrorCallback()
      throw err
    }
  })
}

export async function pauseChat() {
  if (sseCtrl) {
    let token = localStorage.getItem('token')

    sseCtrl?.abort()
    sseCtrl = null
    await axios.get(`/chatV2/ai/interrupt?uuid=${token}`)
  }
}

export async function chatWithHistory(
  model,
  userMsg,
  history,
  systemMsg,
  options = {}
) {
  return ollama.chat({
    model,
    messages: [
      { role: 'system', content: systemMsg },
      ...history,
      { role: 'user', content: userMsg }
    ],
    stream: true
  })
}

export function chat(model, userMsg, systemMsg) {
  return ollama.chat({
    model,
    messages: [
      { role: 'system', content: systemMsg },
      { role: 'user', content: userMsg }
    ],
    stream: true
  })
}

export function listModels() {
  return ollama.list()
}

export function abort() {
  ollama.abort()
}
